package org.irri.smta.report;

import java.io.Writer;
import java.util.Collections;
import java.util.List;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

public class SmtaBuilder {

	public ObjectFactory smtaFactory = new ObjectFactory();

	public Smta createSmtaShell() {
		Smta smta = smtaFactory.createSmta();

		Smta.Provider provider = smtaFactory.createSmtaProvider();
		smta.setProvider(provider);

		Smta.Recipient recipient = smtaFactory.createSmtaRecipient();
		smta.setRecipient(recipient);
		
		Smta.Annex1 annex1 = smtaFactory.createSmtaAnnex1();
		smta.setAnnex1(annex1);

		Smta.Document document = smtaFactory.createSmtaDocument();
		smta.setDocument(document);

		return smta;
	}
	
	private XStream createXStream(Boolean addCdata, List<String> tags) {
		if (addCdata) {
			XStream xstream = new XStream(new XppDriver() {
				public HierarchicalStreamWriter createWriter(Writer out) {
					return new PrettyPrintWriter(out) {
						boolean cdata = false;

						@SuppressWarnings("rawtypes")
						public void startNode(String name, Class clazz) {
							super.startNode(name, clazz);
							cdata = !name.equals("pdf");
						}

						protected void writeText(QuickWriter writer, String text) {
							if (cdata) {
								writer.write("<![CDATA[");
								writer.write(text);
								writer.write("]]>");
							} else {
								writer.write(text);
							}
						}
					};
				}
			});
			return xstream;
		} else {
			return new XStream();
		}
	}

	public String createXml(Smta smta, String encoding) throws Exception {
		XStream xstream = createXStream(false, Collections.<String> emptyList());
		xstream.alias("smta", Smta.class);
		xstream.alias("provider", Smta.Provider.class);
		xstream.alias("recipient", Smta.Recipient.class);
		xstream.alias("annex1", Smta.Annex1.class);
		xstream.alias("material", Smta.Annex1.Material.class);
		xstream.alias("document", Smta.Document.class);
		xstream.addImplicitCollection(Smta.Annex1.class, "material");

		StringBuffer xmlbuf = new StringBuffer();
		xmlbuf.append("<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>");
		xmlbuf.append(System.getProperty("line.separator"));
		xmlbuf.append(xstream.toXML(smta));
		String xml = xmlbuf.toString();
		byte[] utf8Bytes = xml.getBytes(encoding);
		String utf8Xml = new String(utf8Bytes, encoding);

		return utf8Xml;
	}

}
